const { Result } = require('../lib/entity.js');
const { UrlAdapter } = require('../lib/mvcEntity.js');
const mvcUtil = require('../lib/mvcUtil.js');
let router = {
    "routerHandlerList":[],
    "notFindController":null,
    "filterList":[]
};


router.urlAdapter = new UrlAdapter();
let RouterHandler = function(url,controller){
    this.url = url;
    this.controller = controller;
};
let FilterHandler = function(url,filter){
    this.url = url;
    this.filter = filter;
};


router.doAction = async function(request,response){
    let rqUrl = mvcUtil.getRequestUrl(request);
    for(var rhix in router.filterList){
        var filterHandler = router.filterList[rhix];
        if(router.urlAdapter.adapter(rqUrl,filterHandler.url)){
            var filterFlag = await filterHandler.filter.doFilter(request,response);
            if(!filterFlag){
                //没有通过，直接return即可
                return;
            }
        }
    }
    for(var rhix in router.routerHandlerList){
        var rh = router.routerHandlerList[rhix];
        if(router.urlAdapter.adapter(rqUrl,rh.url)){
            return rh.controller.doAction(rh.url,rqUrl,request,response);
        }
    }
    if(router.notFindController){
        router.notFindController.doAction(null,rqUrl,request,response);
    }
};
function findController(cname,finder){
    if(!cname) return null;
    if(finder){
        return finder.findController(cname);
    }else{
        let controller = require(cname);
        return controller;
    }
}
function findFilter(cname,finder){
    if(!cname) return null;
    if(finder){
        return finder.findFilter(cname);
    }else{
        let filter = require(cpl);
        return filter;
    }
}
router.init = function(routerConfig,controllerFinder,filterFinder){
    // 这里简单处理
    for(let rix  in routerConfig.filterList){
        let rm = routerConfig.filterList[rix];
        let requestUrl = rm.mapping_url;
        let cpl = rm.mapping_name;
        let filter = findFilter(cpl,filterFinder);
        
        router.filterList.push(new FilterHandler(requestUrl,filter));
    }
    for(let rix  in routerConfig.mapping){
        let rm = routerConfig.mapping[rix];
        let requestUrl = rm.mapping_url;
        let cpl = rm.mapping_name;
        let controller = findController(cpl,controllerFinder);
        router.routerHandlerList.push(new RouterHandler(requestUrl,controller));
    }
    if(routerConfig.errorConfig && routerConfig.errorConfig.notFind){
        router.notFindController = findController(routerConfig.errorConfig.notFind,controllerFinder);
    }
    
}


module.exports = router;